package com.example.api.controller;

import com.example.service.entity.SystemTenant;
import com.example.service.entity.User;
import com.example.service.service.UserService;
import com.example.service.service.SystemTenantService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.example.api.dto.UserCreateDTO;
import javax.validation.Valid;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.time.LocalDateTime;

/**
 * 用户控制器
 * 提供用户相关的REST API接口
 * 
 * @author example
 * @since 1.0.0
 */
@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户相关的API接口，包括创建、查询、更新和删除用户等操作")
public class UserController {

    @Autowired
    private SystemTenantService systemTenantService;

    private final UserService userService;

    /**
     * 构造函数注入UserService
     * 
     * @param userService 用户服务
     */
    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 创建新用户
     * 
     * @param userDTO 用户创建DTO
     * @return 创建成功的用户对象
     */
    @PostMapping
    @Operation(summary = "创建用户", description = "创建一个新用户")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "201", description = "用户创建成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误")
    })
    public ResponseEntity<User> createUser(@Valid @RequestBody UserCreateDTO userDTO) {
        try {
            User user = new User();
            SystemTenant systemTenant = systemTenantService.findTenantById(userDTO.getTenantId())
                    .orElseThrow(() -> new RuntimeException("租户不存在"));
            user.setTenant(systemTenant);
            user.setUsername(userDTO.getUsername());
            user.setNickname(userDTO.getNickname());
            user.setPassword(userDTO.getPassword());
            user.setEmail(userDTO.getEmail());
            user.setPhone(userDTO.getPhone());
            user.setName(userDTO.getName());
            
            User createdUser = userService.createUser(user);
            return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取所有用户
     * 
     * @return 用户列表
     */
    @Operation(summary = "获取所有用户", description = "获取系统中所有用户的列表")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取用户列表", 
                    content = @Content(schema = @Schema(implementation = List.class)))
    })
    @GetMapping
    public ResponseEntity<List<User>> getAllUsers() {
        List<User> users = userService.findAllUsers();
        return new ResponseEntity<>(users, HttpStatus.OK);
    }

    /**
     * 根据ID获取用户
     * 
     * @param id 用户ID
     * @return 用户对象
     */
    @Operation(summary = "根据ID获取用户", description = "根据用户ID获取用户详细信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取用户信息", 
                    content = @Content(schema = @Schema(implementation = User.class))),
        @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(
            @Parameter(description = "用户ID", required = true, example = "1") 
            @PathVariable Long id) {
        Optional<User> userOptional = userService.findUserById(id);
        return userOptional
                .map(user -> new ResponseEntity<>(user, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 根据用户名获取用户
     * 
     * @param username 用户名
     * @return 用户对象
     */
    @Operation(summary = "根据用户名获取用户", description = "根据用户名获取用户详细信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取用户信息", 
                    content = @Content(schema = @Schema(implementation = User.class))),
        @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @GetMapping("/username/{username}")
    public ResponseEntity<User> getUserByUsername(
            @Parameter(description = "用户名", required = true, example = "admin") 
            @PathVariable String username) {
        Optional<User> userOptional = userService.findUserByUsername(username);
        return userOptional
                .map(user -> new ResponseEntity<>(user, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 根据邮箱获取用户
     * 
     * @param email 邮箱
     * @return 用户对象
     */
    @Operation(summary = "根据邮箱获取用户", description = "根据邮箱获取用户详细信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取用户信息", 
                    content = @Content(schema = @Schema(implementation = User.class))),
        @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @GetMapping("/email/{email}")
    public ResponseEntity<User> getUserByEmail(
            @Parameter(description = "邮箱", required = true, example = "admin@example.com") 
            @PathVariable String email) {
        Optional<User> userOptional = userService.findUserByEmail(email);
        return userOptional
                .map(user -> new ResponseEntity<>(user, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 更新用户信息
     * 
     * @param id 用户ID
     * @param user 用户对象
     * @return 更新后的用户对象
     */
    @Operation(summary = "更新用户信息", description = "更新指定ID的用户信息，用户名和邮箱必须唯一")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "用户信息更新成功", 
                    content = @Content(schema = @Schema(implementation = User.class))),
        @ApiResponse(responseCode = "400", description = "请求参数错误，如用户不存在或用户名/邮箱已被其他用户使用"),
        @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(
            @Parameter(description = "用户ID", required = true, example = "1") 
            @PathVariable Long id, 
            @RequestBody User user) {
        // 确保ID一致
        if (!id.equals(user.getId())) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        
        try {
            User updatedUser = userService.updateUser(user);
            return new ResponseEntity<>(updatedUser, HttpStatus.OK);
        } catch (IllegalArgumentException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 删除用户
     * 
     * @param id 用户ID
     * @return 操作结果
     */
    @Operation(summary = "删除用户", description = "删除指定ID的用户")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "204", description = "用户删除成功"),
        @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(
            @Parameter(description = "用户ID", required = true, example = "1") 
            @PathVariable Long id) {
        boolean deleted = userService.deleteUser(id);
        return deleted 
                ? new ResponseEntity<>(HttpStatus.NO_CONTENT)
                : new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    /**
     * 检查用户名是否已存在
     * 
     * @param username 用户名
     * @return 检查结果
     */
    @Operation(summary = "检查用户名是否存在", description = "检查指定的用户名是否已被使用")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "检查完成", 
                    content = @Content(schema = @Schema(implementation = Map.class)))
    })
    @GetMapping("/check/username/{username}")
    public ResponseEntity<Map<String, Boolean>> checkUsernameExists(
            @Parameter(description = "用户名", required = true, example = "admin") 
            @PathVariable String username) {
        boolean exists = userService.isUsernameExists(username);
        return new ResponseEntity<>(Map.of("exists", exists), HttpStatus.OK);
    }

    /**
     * 检查邮箱是否已存在
     * 
     * @param email 邮箱
     * @return 检查结果
     */
    @Operation(summary = "检查邮箱是否存在", description = "检查指定的邮箱是否已被使用")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "检查完成", 
                    content = @Content(schema = @Schema(implementation = Map.class)))
    })
    @GetMapping("/check/email/{email}")
    public ResponseEntity<Map<String, Boolean>> checkEmailExists(
            @Parameter(description = "邮箱", required = true, example = "admin@example.com") 
            @PathVariable String email) {
        boolean exists = userService.isEmailExists(email);
        return new ResponseEntity<>(Map.of("exists", exists), HttpStatus.OK);
    }
} 